let prefix = 'yyz_';
let device;
import browser from './browser.js';
import Clipboard from 'clipboard';
if (browser.android()) {
  device = 'android_';
} else if (browser.ios()) {
  device = 'ios_';
}
export const getUrlParam = (name) => {
  let r = null, reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  r = window.location.search.substr(1).match(reg);
  if(r == null) r = window.location.hash.substr(1).match(reg);
  return r != null ? unescape(r[2]) : null;
}

export const json2Param = (jsonObj) => {
  return Object.keys(jsonObj).map((k) => {
    return encodeURIComponent(k) + '=' + encodeURIComponent(jsonObj[k]);
  }).join('&');
}

export const addUrlParam = (url, param) => {
  let paramStr = json2Param(param);
  if (url.indexOf('?') >= 0) {
    return url + '&' + paramStr;
  }
  return url + '?' + paramStr;
}

export const removeUrlParam = (url, param) => {
  if (url.indexOf('?') != -1) {
    let str = url.substr(url.indexOf('?') + 1);
    if (str.indexOf('&') != -1) {
      let arr = str.split('&'), rurl = '';
      for (let i in arr) {
        if (arr[i].split('=')[0] != param) {
          rurl = rurl + arr[i].split('=')[0] + '=' + arr[i].split('=')[1] + '&';
        }
      }
      return url.substr(0, url.indexOf('?')) + '?' + rurl.substr(0, rurl.length - 1);
    }
  }
  return url;
}

export const px2rem = (px) => {
  let r = [];
  px = px.toString().trim();
  px = px.split(' ');
  px.forEach((v) => {
    v = parseFloat(v.replace('px', ''));
    v = (v / 37.5).toFixed(5) + 'rem';
    r.push(v);
  });
  return r.join(' ');
};

export const cookie = {
  set: (key, val, expires) => {
    let cookieStr = '';
    cookieStr += encodeURIComponent(prefix + key.toLowerCase()) + '=' + encodeURIComponent(val);
    if (expires) {
      let d = new Date();
      d.setTime(d.getTime() + (expires * 1000));
      cookieStr += '; expires=' + d.toGMTString();
    }
    cookieStr += '; path=/';
    document.cookie = cookieStr;
  },
  
  get: (key) => {
    let name = encodeURIComponent(prefix + key.toLowerCase());
    let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    let arr = document.cookie.match(reg);
    if (arr) return unescape(arr[2]);
    return null;
  },
  
  remove: function(key) {
    this.set(key, '', -1);
  }
}

export const storage = {
  set: (key, val) => {
    if (typeof val === 'object') val = JSON.stringify(val);
    localStorage.setItem(prefix + device + key.toLowerCase(), val);
  },
  
  get: (key) => {
    let r = localStorage.getItem(prefix + device + key.toLowerCase());
    try {
      return JSON.parse(r);
    } catch {
      return r;
    }
  },
  
  remove: (key) => {
    return localStorage.removeItem(prefix + device + key.toLowerCase());
  }
}

export const isRealName = (val) => {
  return /^[\u4e00-\u9fa5]{1,10}$|^[\dA-Za-z]{2,20}$/.test(val);
}

export const isName = (val) => {
  return /^([\u4e00-\u9fa5]{2,8})$/.test(val);
}

export const isPhoneNum = (val) => {
  return /^1[3456789]\d{9}$/.test(val);
}

export const isEmail = (val) => {
  return /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(val);
}

export function formatDate (time, fmt) {
  let date = new Date(time);
  let y = date.getFullYear();
  let MM = date.getMonth() + 1;
  MM = MM < 10 ? ('0' + MM) : MM;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let m = date.getMinutes();
  m = m < 10 ? ('0' + m) : m;
  let s = date.getSeconds();
  s = s < 10 ? ('0' + s) : s;
  let str = fmt.split('-');
  let res = '';
  for (let i in str) {
    if(str[i] == 'yyyy'){
      res = y;
    }else if(str[i] == 'mm') {
      if(res == '') {
        res =  MM;
      }else {
        res = res +'-' + MM;
      }
    }else if(str[i] == 'dd') {
      if(res == '') {
        res =  d;
      }else {
        res = res +'-' + d;
      }
    }else if(str[i] == 'h') {
      if(res == '') {
        res =  h;
      }else {
        res = res +'-' + h;
      }
    }else if(str[i] == 'm') {
      if(res == '') {
        res =  m;
      }else {
        res = res +':' + m;
      }
    }else if(str[i] == 's') {
      if(res == '') {
        res =  s;
      }else {
        res = res +':' + s;
      }
    }
  }
  return res;
}

export const copy = {
  elCopy: (el) => {
    var Url2 = document.getElementById(el).innerText;
    if (typeof(Url2) != 'number') {
      if (Url2.search("<br/>") != -1 ) {
        Url2 = Url2.replace("<br/>","");
      }
    }
    var oInput = document.createElement("input");
    oInput.setAttribute("readonly","readonly");
    oInput.value = Url2;
    oInput.style.opacity = '0';
    oInput.style.position = 'absolute';
    oInput.style.top = '0';
    oInput.style.zIndex = '-1';
    document.body.appendChild(oInput);
    if (browser.ios()) {
      window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
      var range = document.createRange();
      // 选中需要复制的节点
      range.selectNode(oInput);
      // 执行选中元素
      window.getSelection().addRange(range);
      // 执行 copy 操作
      var successful = document.execCommand('copy');// 执行浏览器复制命令
      // 移除选中的元素
      window.getSelection().removeAllRanges();
      console.log(successful);
    } else if (browser.android()) {
      oInput.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      oInput.className = "oInput";
      // oInput.style.display = "none";
    }
    // oInput.style.display = "none";
  },
  dataCopy: (data) => {
    if (typeof(data) != 'number') {
      if (data.search("<br/>") != -1 ) {
        data = data.replace("<br/>",""); 
      }
    }
    var oInput = document.createElement("input");
    oInput.setAttribute("readonly","readonly");
    oInput.value = data;
    oInput.style.opacity = '0';
    oInput.style.position = 'absolute';
    oInput.style.top = '0';
    oInput.style.width = '50px';
    oInput.style.zIndex = '-1';
    document.body.appendChild(oInput);
    if (browser.android()) {
      oInput.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      oInput.className = "oInput";
      // oInput.style.display = "none";
    } else {
      window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
      var range = document.createRange();
      // 选中需要复制的节点
      range.selectNode(oInput);
      // 执行选中元素
      window.getSelection().addRange(range);
      // 执行 copy 操作
      var successful = document.execCommand('copy');// 执行浏览器复制命令
      // 移除选中的元素
      window.getSelection().removeAllRanges();
      alert(successful);
      console.log(successful);
    }
  },
  clipCopy: (el, txtel) => {  // el为点击的按钮类名 txtel为要复制的内容的input的id
    var btn = document.querySelector(el)
    btn.setAttribute('data-clipboard-target',txtel)
    var clipboard = new Clipboard(el);
    clipboard.on('success', function(e) {
      console.info('Text:', e.text);
      e.clearSelection();
      clipboard.destroy();
    });
    clipboard.on('error', function(e) {
      clipboard.destroy();
    });
  }
}
    /**
     * 时间: 2019年12月20日10:28:38
     * 作者: niezhangxun
     * 动态创建iframe
     * @param dom 创建iframe的容器，即在dom中创建iframe。dom能够是div、span或者其它标签。
     * @param src iframe中打开的网页路径
     * @param onload iframe载入完后触发该事件。能够为空
     * @return 返回创建的iframe对象
     */
export function createIframe (dom, src, onload) {
  //在document中创建iframe
  var iframe = document.createElement("iframe");
  //添加id
  iframe.setAttribute('id','iframe')
  //设置iframe的样式
  iframe.style.width = "100%";
  iframe.style.height = "100%";
  iframe.style.margin = "0";
  iframe.style.padding = "0";
  iframe.style.overflow = "hidden";
  iframe.style.border = "none";
  iframe.style.position = "absolute";
  iframe.style.top = "0";
  iframe.style.left = "0";
  iframe.style.zIndex = "100";

  //绑定iframe的onload事件,处理事件的兼容问题
  if (onload && Object.prototype.toString.call(onload) === "[object Function]") {
    if (iframe.attachEvent) {
      iframe.attachEvent("onload", onload);
    } else if (iframe.addEventListener) {
      iframe.addEventListener("load", onload);
    } else {
      iframe.onload = onload;
    }
  }

  iframe.src = src;
  //把iframe载入到dom以下
  dom.appendChild(iframe);
  return iframe;
}